//Copyright (c) Jimmy Cao <jcao219@gmail.com>
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include <windows.h>
#include <string.h>
#include <slre.h>
#include <urlencode.h>
#include <stdio.h>
#include <strrep.h>

char *fields[][2] = { {"subject" , "SUBJ" },
                       {"body"    , "BODY" },
                       {"cc"      , "CC"   },
                       {"bcc"     , "BCC"  } };
size_t fields_len = sizeof(fields) / sizeof(*fields);


int main(int argc, char *argv[]) {
    char *lnk;
    char *mailto;
    
    if(argc == 1) { 
        lnk = "";
    } else {  // lnk = " ".join(argv[1:])
        size_t lnk_sz = 1; // null-terminated
        int i;
        for(i = 1; i < argc; i++) {
            if(i > 1) {
                lnk_sz++;  // add a space in the beginning
            }
            lnk_sz += strlen(argv[i]);
        }
        
        if(lnk_sz < 7)  {
            return 1;
        }
        
        lnk = (char*)malloc(lnk_sz);
        int si = 0;
        for(i = 1; i < argc; i++) {
            if(si) {
                lnk[si++] = ' ';
            }
            strcpy(lnk + si, argv[i]);
            si += strlen(argv[i]);
        }
    }
    
    char *lnk_args = lnk;
    // lnk_args contains what's after the ? in the link
    while(*lnk_args) {
        if(*lnk_args == '?')
            break;
        lnk_args++;
    }
    
    size_t args_size = strlen(lnk_args);
    
    // set mailto = the recipient email address 
    // subtract 7 = subtract the initial mailto:
    size_t mailto_size;  // size of the recipient email address
    if((lnk_args - lnk) < 7)
        mailto_size = lnk_args - lnk;
    else
        mailto_size = lnk_args - lnk - 7;
    
    mailto = (char*)malloc(mailto_size + 1);
    size_t offset = (lnk_args - lnk) >= 7 ? 7 : 0;
    strncpy(mailto, lnk + offset, mailto_size);
    mailto[mailto_size] = '\0';
    
    int field_i;
    const char *error;
    char pattern[25];
    
    char *fields_table[fields_len][2];
    
    for(field_i = 0; field_i < (fields_len); field_i++) {
        size_t field_size = 2 + strlen(fields[field_i][1]);
        
        // make SUBJ -> %SUBJ%, for the first item
        fields_table[field_i][0] = (char*)malloc(field_size + 1);
        fields_table[field_i][0][0] = '%'; // first char = %
        fields_table[field_i][0][field_size] = '\0';
        strncpy(fields_table[field_i][0] + 1, fields[field_i][1], field_size - 2);
        fields_table[field_i][0][field_size - 1] = '%';  // second to last char = %
        
        // this second item is for the actual value of the field, from the mailto: link
        fields_table[field_i][1] = (char*)malloc(args_size + 1); // probably inefficient

        snprintf(pattern, sizeof(pattern) / sizeof(*pattern), 
                "%s%s%s", "[?&]", fields[field_i][0], "=([^&]*)");
        error = slre_match(1, pattern, lnk_args, strlen(lnk_args),
                SLRE_STRING, args_size + 1, fields_table[field_i][1]);
        if(error != NULL) {  // assume no-match
            *fields_table[field_i][1] = '\0'; // empty string
        }
    }
    
    // read link.txt file (in the same directory as application)
    char fname[250];
    GetModuleFileName(NULL, fname, 250);
    *(strrchr(fname, '\\') + 1) = 0;
    strcpy(fname + strlen(fname), "link.txt");
    
    
    FILE *fp = fopen(fname, "r");
    char url[300];
    char *last = NULL;
    char *latest = NULL;
    
    if(fp != NULL) {
        if(fgets(url, 300, fp) != NULL) { 
            size_t fi;
            for(fi = 0; fi < sizeof(url); fi++) {
                if(url[fi] == '\0' || url[fi] == '\n' || url[fi] == '\r') {
                    url[fi] = '\0';
                    break;
                }  // stop reading when there's a break
            }
            last = url;
            for(field_i = 0; field_i < fields_len; field_i++) {
                char *field_value = url_encode(fields_table[field_i][1]);
                latest = str_replace(last,
                        fields_table[field_i][0], 
                        field_value);
                free(field_value);
                if(latest != NULL && last != url) {
                    free(last);
                    last = latest;
                } else if (latest != NULL)
                    last = latest;
            }
        }
        
        fclose(fp);
    }
    
    if(fp != NULL && last != NULL) {
        char *e_mailto = url_encode(mailto);
        latest = str_replace(last, "%RECI%", e_mailto);
        free(last);
        free(e_mailto);
        if(latest != NULL) {
            if(!(latest[0] == 'h' || latest[0] == 'H') && strlen(latest) > 3)
                ShellExecute(NULL, "open", latest + 3, NULL, NULL, SW_SHOWNORMAL);
            else
                ShellExecute(NULL, "open", latest, NULL, NULL, SW_SHOWNORMAL);
            free(latest);
        }
    }
    
    free(lnk);
    free(mailto);
    
    for(field_i = 0; field_i < sizeof(fields_table) / sizeof(*fields_table); field_i++){
        free(fields_table[field_i][0]);
        free(fields_table[field_i][1]);
    }
    
    return 0;
}